<?php

namespace app\common\cachemodel\zl4;

use app\common\cachemodel\AppConfig;
use app\common\cachemodel\Goods;
use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Env;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl4HoroscopeReport extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl4_horoscope_report';

    protected $cacheModel = 'horoscope.report';

    /**
     * 添加并入队
     * @param array $data
     * @return false|int
     */
    public function SaveDataAndQueue(array $data = [])
    {
        // $data = [
        //     'uid' => 222,
        //     'rid' => 123,
        //     'type' => 1,    // 类型  1=>72格局判定 2=>用神详解
        //     'hash' => '',    //  Util::getRecodeHashKey($recode) 调用该方法获取
        //     'status' => 1,   // 计算状态  0=>待计算 1=>计算中 2=>计算完成 3=>计算失败      72格局判定 默认入库计算中状态 ｜ 用神详解 默认入库 待计算状态
        //     'order_num' => '',   // 订单编号
        //     'recode_info' => 0,  // 档案信息  json_encode
        // ];
        try
        {
            $delay = 0;
            if ($data['type'] === 2)
            {   // 用神详解
                $recodeInfo = json_decode($data['recode_info'], true);
                $years = [];
                $nowYear = date('Y');
                for ($i = 1; $i <= 20; $i++)
                {
                    $y = $nowYear - $i;
                    if ($y > $recodeInfo['year'])
                    {
                        $years[] = $y;
                    } else
                    {
                        break;
                    }
                }
                if (count($years) <= 3)
                {   // 可选 年份小于等于三 时  自动跳过选择 直接进行计算
                    $data['status'] = 1;
                } else
                {
                    $delay = 1800;
                }
            }

            $id = $this->insertGetId([
                'uid' => $data['uid'],
                'rid' => $data['rid'],
                'type' => $data['type'],
                'hash' => $data['hash'],
                'status' => $data['status'],
                'order_num' => $data['order_num'],
                'recode_info' => $data['recode_info'],
                'create_time' => time(),
            ]);
            // 删除缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['rid'])->rmCache();
            // 发送 计算队列
            Util::queuePush('horoscope_report_calculate', ['id' => $id], $delay);
            //            if ($data['status'] === 1)
            //            {
            //                Util::queuePush('horoscope_report_calculate', ['id' => $id], $delay);
            //            }
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeReport model => SaveDataAndQueue()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return (int)$id;
    }

    /**
     * 更新报告数据
     * @param int $id
     * @param int $rid
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, int $rid, array $data): bool
    {
        try
        {
            $this->where('id', $id)->update($data);
            // 删除缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $rid)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeReport model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取用户档案解锁 报告信息
     * @param array $recode
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getReport(array $recode, array $field = [])
    {
        $recodeHashKey = Util::getRecodeHashKey($recode);

        $reportData = $this->getReportALL((int)$recode['id'], $field);
        foreach ($reportData as $type => $reportDatum)
        {
            if (isset($reportDatum[$recodeHashKey]))
            {
                $reportDatum[$recodeHashKey]['recode_is_change'] = false;
                $reportData[$type] = $reportDatum[$recodeHashKey];
                continue;
            }

            $resData = [];
            foreach ($reportDatum as $reportDatumItem)
            {
                if (empty($resData))
                {
                    $resData = $reportDatumItem;
                } else
                {
                    if ($reportDatumItem['id'] > $resData['id'])
                    {
                        $resData = $reportDatumItem;
                    }
                }
            }

            $resData['recode_is_change'] = true;

            $reportData[$type] = $resData;
        }

        return $reportData;
    }

    /**
     * 通过档案ID与订单编号 获取解锁信息
     * @param       $rid
     * @param       $orderId
     * @param array $field
     * @return array|mixed
     * @throws \Exception
     */
    public function getOrderReport($rid, $orderId, array $field = [])
    {
        $reportData = $this->getReportALL($rid, $field);

        $resData = [];
        foreach ($reportData as $reportDataLists)
        {
            foreach ($reportDataLists as $reportDetailsItem)
            {
                if ($reportDetailsItem['order_num'] === $orderId)
                {
                    $reportDetailsItem['recode_is_change'] = false;
                    $resData = $reportDetailsItem;
                    break(2);
                }
            }
        }

        return $resData;
    }

    /**
     * 获取用户档案解锁报告详情
     * @param       $rid
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getReportALL($rid, array $field = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $rid)->getDataAndSet(function () use ($rid)
        {
            return $this->getReportByDb($rid);
        }, $field);

        if ($data && $field && is_string($data))
        {
            $data = [current($field) => json_decode($data, true)];
        } else
        {
            foreach ($data as $type => $valueStr)
            {
                $data[$type] = json_decode($valueStr, true);
            }
        }
        return $data;
    }

    /**
     * 通过数据库 获取数据
     * @param int $rid
     * @return array
     */
    public function getReportByDb(int $rid)
    {
        try
        {
            $data = $this->where(['rid' => $rid])->order('id asc')->column('uid,type,hash,order_num,content,status,good_years,bad_years,recode_info,create_time,start_time,end_time', 'id');

            $resData = [];
            foreach ($data as $value)
            {
                $value = arrayKeyData2int($value, ['id', 'uid', 'type', 'status', 'create_time', 'start_time', 'end_time']);
                $value['content'] = $value['content'] ? json_decode($value['content'], true) : [];
                $value['recode_info'] = $value['recode_info'] ? json_decode($value['recode_info'], true) : [];
                $value['good_years'] = $value['good_years'] ? explode(',', $value['good_years']) : [];
                $value['bad_years'] = $value['bad_years'] ? explode(',', $value['bad_years']) : [];

                $resData[$value['type']][$value['hash']] = $value;
            }

            foreach ($resData as $type => $resDatum)
            {
                $resData[$type] = json_encode($resDatum, JSON_UNESCAPED_UNICODE);
            }

            return $resData;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeReport model => getReportByDb()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return [];
        }
    }

    /**
     * 获取底部按钮浮窗列表
     */
    public function getTabBtnList(array $btnNames, array $recodeInfo)
    {
        $header = request()->header();
        if ($header['app-type'] === 'android')
        {
            $HoroscopeConfig = (new AppConfig())->configInfo('horoscope');
            $btnSwitch = isset($HoroscopeConfig['recommend_btn_switch']) && $HoroscopeConfig['recommend_btn_switch'] ? (int)$HoroscopeConfig['recommend_btn_switch'] : 0;
            if ($btnSwitch !== 1)
            {
                return [];
            }
        }
        $isHuawei = Util::IsHuaweiAndOppo();
        $goodModel = new Goods();
        // 获取 八字 72格局判定 与 用神详解 解锁信息
        $HoroscopeReportInfo = (new Zl4HoroscopeReport())->getReport($recodeInfo);
        $oss = Env::get('host.photo');
        $btnListConfig = [
            '八字解读' => [
                'icon' => $oss . 'test/horoscope/horoscope_bzjd.png',
                'name' => $isHuawei ? '生辰解读' : (Util::CheckAppVersion('2.10.0') !== '小' ? '国学解读' : '八字解读'),
                'target' => 'local',
                'link' => "horoscope_analysis_info?tab_index=1&rid={$recodeInfo['id']}&need_auth=1",
                'alert_info' => null,
            ],
            '72格局判定' => [
                'icon' => $oss . 'test/horoscope/horoscope_72gjpd.png',
                'name' => $isHuawei ? '格局解读' : '72格局判定',
                'target' => 'local',
                'link' => 'empty',
                'alert_info' => null,
            ],
            '用神详解' => [
                'icon' => $oss . 'test/horoscope/horoscope_ysxj.png',
                'name' => $isHuawei ? '取用详解' : '用神详解',
                'target' => 'local',
                'link' => 'empty',
                'alert_info' => null,
            ],
            '评分起名' => [
                'icon' => $oss . 'test/horoscope/horoscope_pfqm.png',
                'name' => '评分起名',
                'target' => 'local',
                'link' => 'horoscope_name_index?tab_index=1&need_auth=0',
                'alert_info' => null,
            ],
            '吉日吉时' => [
                'icon' => $oss . 'test/horoscope/horoscope_jrjs.png',
                'name' => '吉日吉时',
                'target' => 'local',
                'link' => "horoscope_select_time_index?rid={$recodeInfo['id']}&need_auth=1",
                'alert_info' => null,
            ],
        ];
        $btnList = [];
        foreach ($btnNames as $btnNameItem)
        {
            if (isset($btnListConfig[$btnNameItem]))
            {
                if ($btnNameItem === '评分起名' && (Util::checkAppVersion('2.15.0') === '小' || Util::AppIsPassShowV1()))
                {
                    continue;
                }
                $btnList[$btnNameItem] = $btnListConfig[$btnNameItem];
            }
        }
        //  72格局判定 --------------------------------------------------------------------------------------------
        if (isset($btnList['72格局判定']))
        {
            if (isset($HoroscopeReportInfo[1]))
            {   // 已解锁 72格局判定
                if ($HoroscopeReportInfo[1]['status'] === 2)
                {   // 计算完成
                    $btnList['72格局判定']['link'] = "horoscope_pattern_72_info?rid={$recodeInfo['id']}&need_auth=1";
                } else
                {   // 计算中
                    $btnList['72格局判定']['alert_info'] = [
                        'title_img' => $oss . ($isHuawei ? 'test/horoscope/horoscope_72gjpd_title2.png' : 'test/horoscope/horoscope_72gjpd_title.png'),
                        'content' => $isHuawei ? "格局是指通过个人排盘后呈现出来的整体状态，会对你的人生格局进行综合性的总结。\r\n本内容会针对你的个人档案信息多个维度对你的人生格局给出评分。" : "格局是指八字呈现出来的整体状态，会对你的人生层次和方向进行高度凝练的总结。\r\n本内容会从内格外格多个维度对你的八字给出判断和评分",
                        'btn_title' => '计算中…',
                        'btn_des' => '',
                        'btn_status' => 0,
                    ];
                }
            } else
            {   // 未解锁 获取 商品信息
                $goodInfo = $goodModel->getInfoById(107);
                if (Util::IsIos() && Util::CheckAppVersion('2.9.7') === '大')
                {
                    $btnTitle = floor($goodInfo['now_prize'] * 10) . '准币解锁';
                    $btnDes = $goodInfo['or_prize'] > $goodInfo['now_prize'] ? floor($goodInfo['or_prize'] * 10) . '准币' : '';
                } else
                {
                    $btnTitle = ((float)$goodInfo['now_prize']) . '元解锁';
                    $btnDes = $goodInfo['or_prize'] > $goodInfo['now_prize'] ? ((float)$goodInfo['or_prize']) . '元' : '';
                }
                $btnList['72格局判定']['link'] = "pay_order?type=28&rid={$recodeInfo['id']}&gid=107&need_auth=1";
                $btnList['72格局判定']['alert_info'] = [
                    'title_img' => $oss . ($isHuawei ? 'test/horoscope/horoscope_72gjpd_title2.png' : 'test/horoscope/horoscope_72gjpd_title.png'),
                    'content' => $isHuawei ? "格局是指通过个人排盘后呈现出来的整体状态，会对你的人生格局进行综合性的总结。\r\n本内容会针对你的个人档案信息多个维度对你的人生格局给出评分。" : "格局是指八字呈现出来的整体状态，会对你的人生层次和方向进行高度凝练的总结。\r\n本内容会从内格外格多个维度对你的八字给出判断和评分",
                    'btn_title' => $btnTitle,
                    'btn_des' => $btnDes,
                    'btn_status' => 1,
                ];
            }
        }
        //  用神详解 --------------------------------------------------------------------------------------------
        if (isset($btnList['用神详解']))
        {
            if (isset($HoroscopeReportInfo[2]))
            {   // 已解锁 用神详解
                if (in_array($HoroscopeReportInfo[2]['status'], [0, 2], true))
                {   // 计算完成
                    $btnList['用神详解']['link'] = "horoscope_yongshen_info?rid={$recodeInfo['id']}&need_auth=1";
                } else
                {   // 计算中
                    $btnList['用神详解']['alert_info'] = [
                        'title_img' => $oss . ($isHuawei ? 'test/horoscope/horoscope_ysxj_title2.png' : 'test/horoscope/horoscope_ysxj_title.png'),
                        'content' => $isHuawei ? "取用详解就是你个人排盘信息中体现出来的：你喜欢的，对你最有用的核心部分。\r\n本内容会针对你的档案信息帮你判断自身及发展的影响因素，教你如何改善。" : "用神就是你喜欢的、对你有用的五行或干支，是八字论断最核心的部分，弄清用神可以帮你判断运势吉凶、教你如何改善和调整命运。",
                        'btn_title' => '计算中…',
                        'btn_des' => '',
                        'btn_status' => 0,
                    ];
                }
            } else
            {   // 未解锁 获取 商品信息
                $goodInfo = $goodModel->getInfoById(106);
                if (Util::IsIos() && Util::CheckAppVersion('2.9.7') === '大')
                {
                    $btnTitle = floor($goodInfo['now_prize'] * 10) . '准币解锁';
                    $btnDes = $goodInfo['or_prize'] > $goodInfo['now_prize'] ? floor($goodInfo['or_prize'] * 10) . '准币' : '';
                } else
                {
                    $btnTitle = ((float)$goodInfo['now_prize']) . '元解锁';
                    $btnDes = $goodInfo['or_prize'] > $goodInfo['now_prize'] ? ((float)$goodInfo['or_prize']) . '元' : '';
                }
                $btnList['用神详解']['link'] = "pay_order?type=28&rid={$recodeInfo['id']}&gid=106&need_auth=1";
                $btnList['用神详解']['alert_info'] = [
                    'title_img' => $oss . ($isHuawei ? 'test/horoscope/horoscope_ysxj_title2.png' : 'test/horoscope/horoscope_ysxj_title.png'),
                    'content' => $isHuawei ? "取用详解就是你个人排盘信息中体现出来的：你喜欢的，对你最有用的核心部分。\r\n本内容会针对你的档案信息帮你判断自身及发展的影响因素，教你如何改善。" : "用神就是你喜欢的、对你有用的五行或干支，是八字论断最核心的部分，弄清用神可以帮你判断运势吉凶、教你如何改善和调整命运。",
                    'btn_title' => $btnTitle,
                    'btn_des' => $btnDes,
                    'btn_status' => 1,
                ];
            }
        }

        return array_values($btnList);
    }

    /**
     * 内容去重
     * @param array $tagList
     * @return array
     */
    public function tagListUnique(array $tagList)
    {
        $textList = [];
        $resData = [];
        foreach ($tagList as $tagListItem)
        {
            if (!in_array($tagListItem['name'], $textList, true))
            {
                $textList[] = $tagListItem['name'];
                $resData[] = $tagListItem;
            }
        }
        return $resData;
    }
}
